import json
import uuid
from datetime import datetime
from Model.default import get_db
from Model.mysocketio.info import Double_Message
from MyRedis.main import get_redis_client


async  def send_double_message(ws,data,socketpool):
    try:
        db=get_db()
        room_id=data.get("room_id")
        receiver_id=data['receiver_id']
        sender_id=data['user_id']
        # 信息传输

        # 发送消息到redis
        redis_client = get_redis_client()
        message_id = redis_client.xadd(room_id,
                                       {
                                           'message': data['content'],
                                           'receiver': receiver_id,
                                           'sender_id': sender_id,
                                           'room_type': 'double',
                                           'room_id':room_id,

                                       }
                                    )
        # 可用于拓展业务
        receiver_socket = socketpool.get(room_id, None)
        # 可用于拓展
        await ws.send_json(
            {
                'type':'message_callback',
                'data':{
                     'status':True,
                     'sender_id':sender_id,
                     'message_type':'Double_Message',
                     'receiver':receiver_id,
                     'messages_id':message_id.decode('utf-8'),
                     'room_id':room_id,
                     'room_type': 'double'
                 }

             }
        )
        # 对于数据库的操作
        new_message = Double_Message(
                id=str(uuid.uuid4()),
                timestamp =str(datetime.now()),
                content = data["content"],
                room_id = data["room_id"],
                receiver_id = int(data["receiver_id"]),
                sender_id = int(data["sender_id"]),
                )
        db.add(new_message)
        db.commit()
    except Exception as e:
        print(e)
        db.rollback()
        pass
    finally:
        db.close()
